<script setup lang="ts">
// import type { PromptsProps } from 'ant-design-x-vue'
import { theme } from 'ant-design-vue'
import {
  useXAgent,
  useXChat,
} from 'ant-design-x-vue'
import { computed, ref, watch } from 'vue'
import ChatSidebar from '../components/ChatSidebar.vue'
import ChatMessageArea from '../components/ChatMessageArea.vue'


const { token } = theme.useToken()

const styles = computed(() => {
  return {
    'layout': {
      'width': '100%',
      'min-width': '670px',
      'max-width': '970px',
      'height': '722px',
      'border-radius': `${token.value.borderRadius}px`,
      'display': 'flex',
      'margin': '0 auto',
      'background': `${token.value.colorBgContainer}`,
      'font-family': `AlibabaPuHuiTi, ${token.value.fontFamily}, sans-serif`,
    },
  } as const
})

defineOptions({ name: 'PlaygroundIndependentSetup' })

const sleep = () => new Promise(resolve => setTimeout(resolve, 500))

const defaultConversationsItems = [
  {
    key: '0',
    label: 'What is CodeWin?',
  },
]

// ==================== State ====================
const content = ref('')
const conversationsItems = ref(defaultConversationsItems)
const activeKey = ref(defaultConversationsItems[0]?.key)
const agentRequestLoading = ref(false)

// ==================== Runtime ====================
const [agent] = useXAgent<string, { message: string }, string>({
  request: async ({ message }, { onSuccess }) => {
    agentRequestLoading.value = true
    await sleep()
    agentRequestLoading.value = false
    onSuccess([`Mock success return. You said: ${message}`])
  },
})

const { onRequest, messages , setMessages } = useXChat({
  agent: agent!.value!,
})

watch(activeKey, () => {
  if (activeKey.value !== undefined) {
    setMessages([])
  }
}, { immediate: true })

// ==================== Event ====================
function onSubmit(nextContent: string) {
  if (!nextContent)
    return
  onRequest(nextContent)
  content.value = ''
}

function onPromptsItemClick(description: string) {
  onRequest(description)
}

function onAddConversation() {
  conversationsItems.value = [
    ...conversationsItems.value,
    {
      key: `${conversationsItems.value.length}`,
      label: `New Conversation ${conversationsItems.value.length}`,
    },
  ]
  activeKey.value = `${conversationsItems.value.length - 1}`
}

function onConversationClick(key: string) {
  activeKey.value = key
}

function handleChange(value: string) {
  content.value = value
}
</script>

<template>
  <div :style="styles.layout">
    <!-- 侧边栏 -->
    <ChatSidebar
      :conversations-items="conversationsItems"
      :active-key="activeKey"
      @add-conversation="onAddConversation"
      @active-change="onConversationClick"
    />

    <!-- 主聊天区域 -->
    <ChatMessageArea 
      :messages="messages"
      :content="content"
      :loading="agentRequestLoading"
      @submit="onSubmit"
      @change="handleChange"
      @prompt-click="onPromptsItemClick"
    />
  </div>
</template>